<!-- 我的培训 -->
<template>
  <div v-loading="loading" class="train-container">
    <div class="tab-bar">
      <CustomTabs :tabList="tabList" :activeName="activeName" @tabSelect="handelTabSelected" />
    </div>
    <div ref="searchRef" class="flex-center table-top">
      <SearchFrom ref="searchFormRef" @search="search" />
    </div>
    <div v-if="tableData.length > 0" class="course-container">
      <px-card v-for="item in tableData" :key="item.id" class="course-item">
        <px-image class="course-img" :src="item.coverJSON !== null ? item.coverJSON[0]?.fileUrl : ''">
          <template #error>
            <div class="image-slot">
              <px-icon><Picture /></px-icon>
            </div>
          </template>
        </px-image>
        <div class="course-info">
          <p class="train-name">{{ item.name }}</p>
          <p>{{ item.typeName }}</p>
          <p v-if="item.state === 'N'">培训时长：{{ formateSeconds(item.period) }}</p>
          <p v-if="item.state === 'S'">学习进度：{{ formateSeconds(item.progress) }} / {{ formateSeconds(item.period) }}</p>
          <p v-if="item.state === 'C'">完成时间：{{ item.completeTime }}</p>
          <p>距离培训结束剩余：{{ item.overdueDaysText ?? "-" }}</p>
        </div>
        <px-button v-if="item.state === 'N'" v-has="'ALL_TRAINMANAGE_MYTRAIN_BTN_STUDY'" class="course-btn" type="primary" @click="toStudy(item)"
          >开始学习</px-button
        >
        <px-button
          v-if="item.state === 'S'"
          v-has="'ALL_TRAINMANAGE_MYTRAIN_BTN_STUDY'"
          class="course-btn"
          type="primary"
          @click="continueStudy(item)"
          >继续学习</px-button
        >
        <px-button
          v-if="item.state === 'C' && item.examName"
          v-has="'ALL_TRAINMANAGE_MYTRAIN_BTN_STUDY'"
          class="course-btn"
          type="primary"
          @click="toExam(item)"
          >去考试</px-button
        >
      </px-card>
    </div>
    <div v-else class="course-container empty-container">
      <px-empty />
    </div>
    <pagination v-show="total > 0" v-model:page="pageNum" v-model:limit="pageSize" class="table-pagination" :total="total" @pagination="search" />
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import SearchFrom from "../component/searchForm.vue";
import CustomTabs from "@/components/Tabs/index.vue";
import { useRouter } from "vue-router";
import { getMyTrainListAPI } from "@/api/knowledge/train";
import { formateSeconds } from "../../trainManage/utils";
import { canExamAPI } from "@/api/knowledge/train";

defineOptions({
  name: "ALL_TRAINMANAGE_MYTRAIN"
});
const router = useRouter();
const tabList = ref([
  { name: "N", label: "未完成" },
  { name: "C", label: "已完成" }
]);
const activeName = ref("N");

const searchFormRef = ref();
const searchRef = ref();

const state = reactive({
  loading: false,
  tableData: [],
  pageNum: 1,
  pageSize: 20,
  total: 10
});
const { loading, tableData, pageNum, pageSize, total } = toRefs(state);

onMounted(() => {
  search();
});

// 切换 未完成/已完成
const handelTabSelected = tab => {
  activeName.value = tab;
  search();
};

const search = async p => {
  try {
    state.loading = true;
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    const params = {
      pageSize: state.pageSize,
      pageNum: state.pageNum,
      name: p ? p.name : "",
      type: p ? p.type : "",
      department: p ? p.className : "",
      traineeId: userInfo.userId,
      state: activeName.value
    };
    const res = await getMyTrainListAPI(params);
    if (res?.data?.length) {
      let data = res?.data;
      data?.forEach(i => {
        if (i.overdueDays > 0) {
          i.overdueDaysText = i.overdueDays + "天";
        } else {
          i.overdueDaysText = "逾期" + Math.abs(i.overdueDays) + "天";
        }
      });
      state.tableData = data;
      state.total = res.total;
    } else {
      state.tableData = [];
      state.total = 0;
    }
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

// 去学习
const toStudy = data => {
  router.push({
    path: "/all/knowledge/trainManage/myTrain/detail",
    query: {
      data: JSON.stringify(data)
    }
  });
};

// 继续学习
const continueStudy = data => {
  router.push({
    path: "/all/knowledge/trainManage/myTrain/detail",
    query: {
      data: JSON.stringify(data)
    }
  });
};

const userInfo = JSON.parse(localStorage.getItem("userInfo"));
// 去考试
const toExam = async data => {
  try {
    state.loading = true;
    const params = {
      trainId: data.trainId,
      examId: data.examId,
      traineeId: userInfo.userId
    };
    await canExamAPI(params);
    router.push({
      path: "/all/knowledge/examManage/myExam/exam",
      query: {
        examId: data.examId,
        examineeId: userInfo.userId
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/trainManage/scss/common.scss");

.tab-bar {
  margin-bottom: 16px;
}

.config-step {
  position: relative;
  width: 100%;

  .back-btn {
    position: absolute;
    left: 0;
  }

  .step-container {
    width: 400px;
    margin: 0 auto;
  }

  .step-form {
    position: relative;
    width: 80%;
    height: calc(100vh - 240px);
    padding: 40px 0 20px;
    margin: 0 auto;
  }
}

.course-container {
  display: flex;
  flex: 1 1 auto;
  flex-wrap: wrap;
  align-content: flex-start;
  // align-items: center;
  // justify-content: space-around;
  width: 100%;
  height: calc(100vh - 366px);
  overflow-y: auto;

  .course-item {
    width: 302px;
    // height: 310px;
    margin-right: 16px;
    margin-bottom: 16px;

    .course-img {
      width: 100%;
      height: 180px;

      .image-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
      }
    }

    .course-info {
      width: 100%;
      // height: 88px;
      padding: 8px;
      font-size: 14px;

      .train-name {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .course-btn {
      width: 100%;
      height: 32px;
      border-radius: 0 0 4px 4px;
    }
  }
}

.empty-container {
  justify-content: center;
}

:deep(.px-card__body) {
  padding: 0 !important;
}

:deep(.px-empty__image) {
  display: none;
}

:deep(.px-empty) {
  height: calc(100vh - 366px);
  vertical-align: middle;
}
</style>
